<?php
function geturl2($url){
	
$cookie ="cookie.txt";
$userAgent = 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31' ;
$ch = curl_init($url);
$options = array(
    CURLOPT_CONNECTTIMEOUT => 20 , 
    CURLOPT_USERAGENT => $userAgent,
    CURLOPT_AUTOREFERER => true,
    
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_COOKIEFILE => $cookie,
    CURLOPT_COOKIEJAR => $cookie ,
    CURLOPT_SSL_VERIFYPEER => 0 ,
    CURLOPT_SSL_VERIFYHOST => 0
);
curl_setopt_array($ch, $options);
$str = curl_exec($ch);
curl_close($ch);
return $str;
}

function fetch_anime(){
	$db=new db;
	$db->connect();
	$db->query("select id,name,url,alias,scan_loaibo from anime where scan_auto=1  order by id desc limit 0,1");
	if($db->num_rows()>0){
	 $data=$db->fetchOne();
	 
	if(strpos($data['url'],"vnsharing")!==false){
		$data['urls']=fetch_vnsharing3($data['url'],$data['scan_loaibo']);
	}else
	if(strpos($data['url'],"blogtruyen")!==false){
		$data['urls']=fetch_blogtruyen($data['url'],$data['scan_loaibo']);
	}else
	if(strpos($data['url'],"truyentranhnhanh")!==false){
		$data['urls']=fetch_truyentranhnhanh($data['url'],$data['scan_loaibo']);
	}
	else
	if(strpos($data['url'],"truyentranh8")!==false){
		$data['urls']=fetch_tt8($data['url'],$data['scan_loaibo']);
	}
	//fetch_vnsharing3($data['url']);
	
	return $data;
	}else{
	echo "het roi";
	}
}

	
function fetch_anime2(){
	$db=new db;
	$db->connect();
	$db->query("select id,name,url,alias,scan_loaibo from anime where scan_auto=1  order by id desc limit 0,1");
	if($db->num_rows()>0){
	 $data=$db->fetchOne();
	 
	if(strpos($data['url'],"vnsharing")!==false){
		$data['urls']=fetch_vnsharing3($data['url'],$data['scan_loaibo']);
		
	
		
		
	}else
	if(strpos($data['url'],"blogtruyen")!==false){
		$data['urls']=fetch_blogtruyen($data['url'],$data['scan_loaibo']);
	}
	else
	if(strpos($data['url'],"truyentranhnhanh")!==false){
		$data['urls']=fetch_truyentranhnhanh($data['url'],$data['scan_loaibo']);
	}
	else
	if(strpos($data['url'],"truyentranh8")!==false){
		$data['urls']=fetch_tt8($data['url'],$data['scan_loaibo']);
	}
	//print_r($data['urls']);
	
	//Lay manga ra nhung link bi loi hoac server zing
	//	$db->query("select c.ten,c.thutu,c.check_error,c2.server from chapterk2 as c,chapterk_content as c2 where c.manga=".$data['id']." and c.id=c2.chap_id and c2.server='zing' or c2.check_error=1");
		$db->query("select c.thutu,c.id from chapterk2 as c,chapterk_content as c2 where c.manga=".$data['id']." and c.id=c2.chap_id and (c2.server='zing' or c2.check_error=1)");
		echo mysql_error();
		
		if($db->num_rows()>0){
			$data2=$db->fetchAll();
		
			//Co mang thutu bi loi
			
		}else{ 
			echo "het roi"; exit();
		}
		
	//	print_r($data2);
		foreach($data['urls'] as $val){
			$tt=trim($val['thutu']);
			foreach($data2 as $val2){
				$val['chap_id']=$val2['id'];
				if($tt==$val2['thutu']){ $data3[]=$val;}
			}
			
		}
	
		//Gan lai
		$data['urls']=$data3;
	// Lay nhung link bi loi hoac zing server------
	
	return $data;
	}else{
	echo "het roi";
	}
}

	
//Lay so trong link (episode)
	function get_num($str) {
        preg_match_all('/\d+/', $str, $matches);
        return $matches[0];
    }

	
	

//Get image trong link vnsharing	
	function vnsurl($source)
	{		
				// Lay link image cua chapter do nha :---------------------------------------------------------------
					$mangurl=array();
				//$source=stripcslashes($contents);
				   $source=preg_replace("/\?imgmax=3000/","",$source);
					preg_match_all('/lstImages.push\(\"(.*)\"/i',$source, $media);
					$str="";
					foreach($media[1] as $url)
								{	
									$s="<img src='".$url."' />";
									$str.=$s;
									
								}	
								return  $str;
}


function fetch_vnsharing3($url,$loaibo=''){
	$str=geturl2($url);
	//echo $str;
	$str=str_replace('window.location = "http://truyen.vnsharing.net";','',$str);
	//echo $url;
	//echo $str;
	$html = new simple_html_dom();
	$html->load($str);

	//$e=$html->find('table[class=listing]',0)->find('tr',1)->find('td',0); 
	if(!$html->find('table[class=listing]',0)){
		//Dung phantomjs de getlink
		//Update de biet la getlink playlist nay bi loi, nhap link = tay
		exit();
	}else{
			$e1=$html->find('table[class=listing]',0)->find('tr');
	}
	$data=array();
	$tt=0;
	foreach($e1 as $e){
		if($e->find('td',0)){
			$url="http://truyen.vnsharing.net".$e->find('td',0)->find('a',0)->href;

				$string=$e->find('td',0)->find('a',0)->innertext;
				$string=str_replace($loaibo,'',$string);
						
						preg_match('/(episode|tập|ep|tap|chuong|chapter|)?\d+(?:\.\d+|[abcdef])?/i',$string, $matches);
						if(count($matches)>0){
							$num=$matches[0];
						
							if(is_float($num)){
								$tt=$num;
							}else{
								$num2=floatval($num);
								$sub="";
								if(strpos($num,"a")!==false){
									$sub=".1";
								}
								if(strpos($num,"b")!==false){
									$sub=".2";
								}
								if(strpos($num,"c")!==false){
									$sub=".3";
								}
								if(strpos($num,"d")!==false){
									$sub=".4";
								}
								if(strpos($num,"e")!==false){
									$sub=".5";
								}
								if(strpos($num,"f")!==false){
									$sub=".6";
								}
								$tt= $num2.$sub;
								$name="Chap ".$tt;
							}
						}else{
							
							$name= $string;
							$tt=$tt+0.1;
						}		
									
									
									$row['thutu']=$tt;
									$row['name']=trim($name);
									$row['link']=$url;
										$data[]=$row;
							
							
							
						
					
			
		}
		
	}
	
	//print_r($data);
	return $data;
	
	}

function fetch_blogtruyen($url,$loaibo=''){
	$str=geturl2($url);

	$html = new simple_html_dom();
	$html->load($str);

	
	if(!$html->find('#list-chapters',0)){
		
		exit();
	}else{
			$e1=$html->find('#list-chapters',0);
	}
	$data=array();
	$tt=0;
	foreach($e1->find("a") as $e){
		
			

		
						$url="http://blogtruyen.com".$e->href;
						$string=$e->innertext;
						$string=str_replace($loaibo,'',$string);
						$string=html_entity_decode($string, ENT_COMPAT, 'UTF-8');
						preg_match('/(episode|tập|ep|tap|chuong|chapter|)?\d+(?:\.\d+|[abcdef])?/i',$string, $matches);
						if(count($matches)>0){
							$num=$matches[0];
						
							if(is_float($num)){
								$tt=$num;
							}else{
								$num2=floatval($num);
								$sub="";
								if(strpos($num,"a")!==false){
									$sub=".1";
								}
								if(strpos($num,"b")!==false){
									$sub=".2";
								}
								if(strpos($num,"c")!==false){
									$sub=".3";
								}
								if(strpos($num,"d")!==false){
									$sub=".4";
								}
								if(strpos($num,"e")!==false){
									$sub=".5";
								}
								if(strpos($num,"f")!==false){
									$sub=".6";
								}
								$tt= $num2.$sub;
								$name="Chap ".$num;
							}
						}else{
							
							$name= $string;
							$tt=$tt+0.1;
						}		
									
									
									$row['thutu']=$tt;
									$row['name']=trim($name);
									$row['link']=$url;
								
								
									$data[]=$row;
							
							
							
						
					
			
		
		
	}//End of foreaqch
	
	
	return $data;
	
	}	




function fetch_vuitruyentranh($url,$loaibo=''){
	//get image trong 1 chap ne----
	
			
	
	//End of get image trong 1 chap cua thang vui truyentranh
	
	
	
	$str=geturl2($url);
	
	

	$html = new simple_html_dom();
	$html->load($str);

	
	if(!$html->find('.chap-story-show',0)){
		
		exit();
	}else{
			$e1=$html->find('.chap-story-show',0);
	}
	$data=array();
	$tt=0;
	foreach($e1->find("a") as $e){
		
			

		
						$url=$e->href;
						$string=$e->innertext;
						$string=str_replace($loaibo,'',$string);
						$string=html_entity_decode($string, ENT_COMPAT, 'UTF-8');
						preg_match('/(episode|tập|ep|tap|chuong|chapter|)?\d+(?:\.\d+|[abcdef])?/i',$string, $matches);
						if(count($matches)>0){
							$num=$matches[0];
						
							if(is_float($num)){
								$tt=$num;
							}else{
								$num2=floatval($num);
								$sub="";
								if(strpos($num,"a")!==false){
									$sub=".1";
								}
								if(strpos($num,"b")!==false){
									$sub=".2";
								}
								if(strpos($num,"c")!==false){
									$sub=".3";
								}
								if(strpos($num,"d")!==false){
									$sub=".4";
								}
								if(strpos($num,"e")!==false){
									$sub=".5";
								}
								if(strpos($num,"f")!==false){
									$sub=".6";
								}
								$tt= $num2.$sub;
								$name="Chap ".$num;
							}
						}else{
							
							$name= $string;
							$tt=$tt+0.1;
						}		
									
									
									$row['thutu']=$tt;
									$row['name']=trim($name);
									$row['link']=$url;
								
								
									$data[]=$row;
							
							
							
						
					
			
		
		
	}//End of foreaqch
	
	
	return $data;
	
	}	


function fetch_truyentranhnhanh($url,$loaibo=''){
	$str=geturl2($url);
	$html = new simple_html_dom();
	$html->load($str);

	
	if(!$html->find(".detail_list",0)){
		
		exit();
	}else{
			$e1=$html->find(".detail_list",0)->find('ul',0);
	}
	$data=array();
	$tt=0;
	foreach($e1->find("a") as $e){
		
			

		
						$url=$e->href;
						$string=$e->innertext;
						$string=str_replace($loaibo,'',$string);
						$string=html_entity_decode($string, ENT_COMPAT, 'UTF-8');
						preg_match('/(episode|tập|ep|tap|chuong|chapter|)?\d+(?:\.\d+|[abcdef])?/i',$string, $matches);
						if(count($matches)>0){
							$num=$matches[0];
						
							if(is_float($num)){
								$tt=$num;
							}else{
								$num2=floatval($num);
								$sub="";
								if(strpos($num,"a")!==false){
									$sub=".1";
								}
								if(strpos($num,"b")!==false){
									$sub=".2";
								}
								if(strpos($num,"c")!==false){
									$sub=".3";
								}
								if(strpos($num,"d")!==false){
									$sub=".4";
								}
								if(strpos($num,"e")!==false){
									$sub=".5";
								}
								if(strpos($num,"f")!==false){
									$sub=".6";
								}
								$tt= $num2.$sub;
								$name="Chap ".$num;
							}
						}else{
							
							$name= $string;
							$tt=$tt+0.1;
						}		
									
									
									$row['thutu']=$tt;
									$row['name']=trim($name);
									$row['link']=$url;
								
								
									$data[]=$row;
							
							
							
						
					
			
		
		
	}//End of foreaqch
	
	
	return $data;
	
	}	

function fetch_tt8($url,$loaibo=''){
	//Get content = phantomjs
		$a = '
						var fs = require(\'fs\');
						var page = require(\'webpage\').create();
				page.onConsoleMessage = function(msg) {
					console.log(msg);
				};
				page.settings.loadImages=false;
				page.onResourceRequested = function(request, net) {
					if (request.url.indexOf(\'http://truyentranh8/\') !== 0){
      					 //	net.abort();
							}
				
				}
				page.open("'.$url.'", function(status) {
					if ( status === "success" ) {
					//  console.log(page.content);
							page.evaluate(function() {
								
								console.log( $("#ChapList").html());
								
								
							});
							
							
							phantom.exit();
						
					}
				});';
			
				file_put_contents('ptjs/pt.js', $a);
				exec('phantomjs ptjs/pt.js > ptjs/a.txt');
				$str =file_get_contents('ptjs/a.txt');

	
	
	
	
	
	$html = new simple_html_dom();
	$html->load($str);

	$data=array();
	$tt=0;
	foreach($html->find("a") as $e){
		
			

		
						$url=$e->href;
						$string=$e->title;
						$string=str_replace($loaibo,'',$string);
						$string=html_entity_decode($string, ENT_COMPAT, 'UTF-8');
						preg_match('/(episode|tập|ep|tap|chuong|chapter|)?\d+(?:\.\d+|[abcdef])?/i',$string, $matches);
						if(count($matches)>0){
							$num=$matches[0];
						
							if(is_float($num)){
								$tt=$num;
							}else{
								$num2=floatval($num);
								$sub="";
								if(strpos($num,"a")!==false){
									$sub=".1";
								}
								if(strpos($num,"b")!==false){
									$sub=".2";
								}
								if(strpos($num,"c")!==false){
									$sub=".3";
								}
								if(strpos($num,"d")!==false){
									$sub=".4";
								}
								if(strpos($num,"e")!==false){
									$sub=".5";
								}
								if(strpos($num,"f")!==false){
									$sub=".6";
								}
								$tt= $num2.$sub;
								$name="Chap ".$num;
							}
						}else{
							
							$name= $string;
							$tt=$tt+0.1;
						}		
									
									
									$row['thutu']=$tt;
									$row['name']=trim($name);
									$row['link']=$url;
								
								
									$data[]=$row;
							
							
							
						
					
			
		
		
	}//End of foreaqch
	
	
	return $data;
	
	}	


function tt8_getimage($href){
				$a = '
						var fs = require(\'fs\');
						var page = require(\'webpage\').create();
				page.onConsoleMessage = function(msg) {
					console.log(msg);
				};
				page.settings.loadImages=false;
				page.onResourceRequested = function(request, net) {
					if (request.url.indexOf(\'http://truyentranh8/\') !== 0){
      					 //	net.abort();
							}
				
				}
				page.open("'.$href.'", function(status) {
					if ( status === "success" ) {
					//  console.log(page.content);
							page.evaluate(function() {
								
								console.log( $("#wrapper").html());
								
								
							});
							
							
							phantom.exit();
						
					}
				});';
			
				file_put_contents('ptjs/pt.js', $a);
				exec('phantomjs ptjs/pt.js > ptjs/a.txt');
				$data =file_get_contents('ptjs/a.txt');
				
				
				$data= str_replace('<img src="http://truyentranh8.com/templates/main/images/gioithieubanbe3.png" class="lazy">','',$data);
				$data= str_replace('?imgmax=1600','',$data);
			
				return $data;
			
}